package com.wty.cmims.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wty.cmims.config.AliPayConfig;
import com.wty.cmims.pojo.AliPay;
import com.wty.cmims.pojo.Appointment;
import com.wty.cmims.pojo.Doctor;
import com.wty.cmims.pojo.Orders;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.service.AliPayService;
import com.wty.cmims.service.AppointmentService;
import com.wty.cmims.service.DoctorService;
import com.wty.cmims.service.OrdersService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class AliPayServiceImpl implements AliPayService {
    @Resource
    private OrdersService ordersService;
    @Resource
    private AppointmentService appointmentService;
    @Resource
    private DoctorService doctorService;
    @Resource
    private AliPayConfig aliPayConfig;
    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    @Override
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) {
        // AlipayClient 初始化
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        if (aliPay.getMethod().equals("pc")) {
            // PC端页面请求设置
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                    + "\"total_amount\":\"" + aliPay.getOrderPrice() + "\","
                    + "\"subject\":\"" + aliPay.getSubject() + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            executePayRequest(request, alipayClient, httpResponse);
        } else {
            // 移动端页面请求设置
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                    + "\"total_amount\":\"" + aliPay.getOrderPrice() + "\","
                    + "\"subject\":\"" + aliPay.getSubject() + "\","
                    + "\"product_code\":\"QUICK_WAP_WAY\"}");
            executePayRequest(request, alipayClient, httpResponse);
        }
    }

    @Override
    public String payNotify(HttpServletRequest request) {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            // 支付宝验签
            try {
                if (Factory.Payment.Common().verifyNotify(params)) {
                    // 验签通过
                    System.out.println("交易名称: " + params.get("subject"));
                    System.out.println("交易状态: " + params.get("trade_status"));
                    System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                    System.out.println("商户订单号: " + params.get("out_trade_no"));
                    System.out.println("交易金额: " + params.get("total_amount"));
                    System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                    System.out.println("买家付款时间: " + params.get("gmt_payment"));
                    System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                    // TODO：更新订单已支付的逻辑代码
                    // 商户订单号，就是当前已经支付完成的订单的id号，需要将支付状态修改为已支付
                    if (params.get("subject").equals("药品")) {
                        Orders orders = this.ordersService.getById(Integer.valueOf(tradeNo));
                        if (orders != null) {
                            this.ordersService.ordersStatusUpdate(Integer.valueOf(tradeNo));
                        }
                    }
                    if (params.get("subject").equals("预约挂号")){
                        Appointment appointment = this.appointmentService.getById(Integer.parseInt(tradeNo.substring(2)));
                        if (appointment != null){
                            this.appointmentService.appointmentPayUpdate(Integer.parseInt(tradeNo.substring(2)),params.get("trade_no"));
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return "success";
    }

    @Override
    public ResponseResult<Map<String, Object>> refund(String tradeNo) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        //查询订单信息
        LambdaQueryWrapper<Appointment> appointmentMapper = new LambdaQueryWrapper<>();
        appointmentMapper.eq(Appointment::getId, Integer.parseInt(tradeNo.substring(2)));
        Appointment appointment = appointmentService.getOne(appointmentMapper);
        Doctor doctor = doctorService.getById(appointment.getDoctorId());
        Integer orderPrice = doctor.getFee();

        //创建Client，调用通用SDK提到的Client，用来调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        //创建Request并设置参数
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no", tradeNo);  //我的单号
        jsonObject.put("refund_amount", String.format("%.2f", orderPrice * 1.0));//退款金额
        jsonObject.put("trade_no", appointment.getTradeNo());//支付宝本身的订单流水号
//      jsonObject.put("out_request_no", UUIDGenerator.generateId());   //这个参数需要注意，如果想要实现部分退款逻辑这个参数是必须的
//      request.setBizContent(jsonObject.toString());
        request.setBizContent(jsonObject.toJSONString());
        //执行请求
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            Map<String, Object> map = new HashMap<>();
            map.put("refund_amount", orderPrice * 1.0);
            appointment.setStatus(4);
            appointmentService.updateById(appointment);
            responseResult.setCode(2000);
            responseResult.setMessage("退款成功");
            responseResult.setData(map);
        } else {
            responseResult.setCode(5000);
            responseResult.setMessage("退款失败");
        }
        return responseResult;
    }

    private void executePayRequest(AlipayRequest<?> request, AlipayClient alipayClient, HttpServletResponse httpResponse) {
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());

        // API 调用
        String form = "";
        try {
            // 调用SDK生成支付表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面，跳转至支付宝支付页面。
        try {
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
